﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class frm_Edit_ExportRobotPlan : Form
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private string error;
        public string number;
        public frm_Edit_ExportRobotPlan()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.error = null;
            this.number = null;
            if (string.IsNullOrEmpty(error))
            {
                LoadCurrency();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadDeliveryTerm();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadTransportation();
            }
            if (!string.IsNullOrEmpty(error))
            {
                MessageBox.Show(error);
            }
        }

        ////////////////////////////////////////////
        /// Load Data for Select Record
        ////////////////////////////////////////////
        public bool LoadData()
        {
            bool ret = true;
            if (string.IsNullOrEmpty(number))
            {
                //MessageBox.Show("No Export Robot Plan to edit");
                ret = false;
            }
            else
            {
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT [241_ExportRobotPlan].Number, [241_ExportRobotPlan].OriginalNo, "
                        + " [241_ExportRobotPlan].InputDate, [222_Staff].StaffName, [222_Customer].FullName,"
                        + " [222_ShipTo].ShipToName, [241_ExportRobotPlan].PlanNo, [222_Comp].CompID,"
                        + " [241_ExportRobotPlan].Quantity, [241_ExportRobotPlan].POID, [241_ExportRobotPlan].CusPlanNo,"
                        + " [241_ExportRobotPlan].CusOrderNo, [241_ExportRobotPlan].HopeDeadline, [241_ExportRobotPlan].UnitPrice,"
                        + " [241_ExportRobotPlan].CurrencyID, [241_ExportRobotPlan].DeliveryTermID, [241_ExportRobotPlan].TransportID,"
                        + " [241_ExportRobotPlan].FixDeadline, [241_ExportRobotPlan].F2Deadline, [241_ExportRobotPlan].F5Deadline,"
                        + " [241_ExportRobotPlan].OImportDeadline, [241_ExportRobotPlan].VNImportDeadline,"
                        + " [241_ExportRobotPlan].StoreDeadline, [241_ExportRobotPlan].AssDeadline, [241_ExportRobotPlan].F4Order,"
                        + " [241_ExportRobotPlan].Note"
                        + " FROM [241_ExportRobotPlan], [222_Staff], [222_Customer], [222_ShipTo], [222_Comp]"
                        + " WHERE [241_ExportRobotPlan].Number='" + number + "'"
                        + " AND [241_ExportRobotPlan].InputPerson=[222_Staff].StaffID"
                        + " AND [241_ExportRobotPlan].CustomerID=[222_Customer].CustomerID"
                        + " AND [241_ExportRobotPlan].ShipToCode=[222_ShipTo].ShipToCode"
                        + " AND [241_ExportRobotPlan].RobotNo=[222_Comp].CompID";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    if (dataReader.Read())
                    {
                        this.numberValue.Text = dataReader["Number"].ToString();
                        this.originalNo.Text = dataReader["OriginalNo"].ToString();
                        this.inputDate.EditValue = DateTime.Parse(dataReader["InputDate"].ToString());
                        this.inputPerson.Text = dataReader["StaffName"].ToString();
                        this.customerID.Text = dataReader["FullName"].ToString();
                        this.shipTo.Text = dataReader["ShipToName"].ToString();
                        this.planNo.Text = dataReader["PlanNo"].ToString();
                        this.robotNo.Text = dataReader["CompID"].ToString();
                        this.quantityValue.Text = dataReader["Quantity"].ToString();
                        this.poID.Text = dataReader["POID"].ToString();
                        this.cusPlanNo.Text = dataReader["CusPlanNo"].ToString();
                        this.cusOrderNo.Text = dataReader["CusOrderNo"].ToString();
                        this.hopeDeadline.EditValue = DateTime.Parse(dataReader["HopeDeadline"].ToString());
                        this.unitPrice.Text = dataReader["UnitPrice"].ToString();
                        int i;
                        ComboboxItem item = new ComboboxItem();
                        for (i = 0; i < currencyID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.currencyID.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["CurrencyID"].ToString())
                            {
                                this.currencyID.SelectedIndex = i;
                            }
                        }

                        for (i = 0; i < deliveryTerm.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.deliveryTerm.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["DeliveryTermID"].ToString())
                            {
                                this.deliveryTerm.SelectedIndex = i;
                            }
                        }

                        for (i = 0; i < transportationID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.transportationID.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["TransportID"].ToString())
                            {
                                this.transportationID.SelectedIndex = i;
                            }
                        }

                        if (dataReader["FixDeadline"] != DBNull.Value)
                        {
                            this.fixDeadline.EditValue = DateTime.Parse(dataReader["FixDeadline"].ToString());
                        }
                        if (dataReader["F2Deadline"] != DBNull.Value)
                        {
                            this.f2Deadline.EditValue = DateTime.Parse(dataReader["F2Deadline"].ToString());
                        }
                        if (dataReader["F5Deadline"] != DBNull.Value)
                        {
                            this.f5Deadline.EditValue = DateTime.Parse(dataReader["F5Deadline"].ToString());
                        }
                        if (dataReader["OImportDeadline"] != DBNull.Value)
                        {
                            this.overDeadline.EditValue = DateTime.Parse(dataReader["OImportDeadline"].ToString());
                        }
                        if (dataReader["VNImportDeadline"] != DBNull.Value)
                        {
                            this.vnDeadline.EditValue = DateTime.Parse(dataReader["VNImportDeadline"].ToString());
                        }
                        if (dataReader["StoreDeadline"] != DBNull.Value)
                        {
                            this.storeDeadline.EditValue = DateTime.Parse(dataReader["StoreDeadline"].ToString());
                        }
                        if (dataReader["AssDeadline"] != DBNull.Value)
                        {
                            this.assDeadline.EditValue = DateTime.Parse(dataReader["AssDeadline"].ToString());
                        }
                        this.f4Order.Checked = bool.Parse(dataReader["F4Order"].ToString());                        
                        this.noteValue.Text = dataReader["Note"].ToString();
                    }
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    ret = false;
                    //MessageBox.Show(ex.Message);
                    //error = "Cannot get Load Data for selected record";
                }
            }

            return ret;
        }

        ////////////////////////////////////////////
        /// Load Currency
        ////////////////////////////////////////////
        private void LoadCurrency()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CurrencyID, CurrencySymbol FROM [222_Currency] ORDER BY CurrencySymbol";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CurrencySymbol"].ToString();
                    item.Value = dataReader["CurrencyID"].ToString();
                    this.currencyID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Currency list";
            }
        }

        ////////////////////////////////////////////
        /// Load Delivery Term
        ////////////////////////////////////////////
        private void LoadDeliveryTerm()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT DeliveryTermID, DeliveryTermName FROM [222_DeliveryTerm] ORDER BY DeliveryTermName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["DeliveryTermName"].ToString();
                    item.Value = dataReader["DeliveryTermID"].ToString();
                    this.deliveryTerm.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Delivery Term list";
            }
        }

        ////////////////////////////////////////////
        /// Load Transportation
        ////////////////////////////////////////////
        private void LoadTransportation()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT TransportID, TransportName FROM [222_Transport] ORDER BY TransportName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["TransportName"].ToString();
                    item.Value = dataReader["TransportID"].ToString();
                    this.transportationID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Transportation list";
            }
        }
        
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            string error_add = null;
            if (!string.IsNullOrEmpty(error))
            {
                error_add = error;
            }
            string planno, poid;
            string cusplan, cusorder, delivery, transp, note;
            int currency = -1, f4;
            DateTime? fixdeadline, f2deadline, f5deadline, overdeadline, vndeadline, storedeadline, assdeadline;
            float unitprice = 0;
            ComboboxItem item = new ComboboxItem();            

            if (string.IsNullOrEmpty(error_add))
            {
                if (string.IsNullOrEmpty(this.unitPrice.Text))
                {
                    unitprice = 0;
                }
                else
                {
                    bool isNum = float.TryParse(this.unitPrice.Text, out unitprice);
                    if (!isNum)
                    {
                        error_add = "Invalid Unit Price value";
                    }
                }
            }
            
            
            if (string.IsNullOrEmpty(error_add))
            {               
                planno = this.planNo.Text;
                poid = this.poID.Text;
                cusplan = this.cusPlanNo.Text;
                cusorder = this.cusOrderNo.Text;

                if (this.currencyID.SelectedIndex == -1)
                {
                    for (int i = 0; i < this.currencyID.Properties.Items.Count; i++)
                    {
                        item = (ComboboxItem)this.currencyID.Properties.Items[i];
                        if (item.Text.ToString().Trim().ToUpper() == "NF")
                        {
                            currency = Int32.Parse(item.Value.ToString());
                        }
                    }
                }
                else
                {
                    item = (ComboboxItem)this.currencyID.SelectedItem;
                    currency = Int32.Parse(item.Value.ToString());
                }

                if (this.transportationID.SelectedIndex == -1)
                {
                    transp = "NF";
                }
                else
                {
                    item = (ComboboxItem)this.transportationID.SelectedItem;
                    transp = item.Value.ToString();
                }

                if (this.deliveryTerm.SelectedIndex == -1)
                {
                    delivery = "NF";
                }
                else
                {
                    item = (ComboboxItem)this.deliveryTerm.SelectedItem;
                    delivery = item.Value.ToString();
                }
                
                if (fixDeadline.EditValue == null)
                {
                    fixdeadline = null;
                }
                else
                {
                    fixdeadline = DateTime.Parse(this.fixDeadline.DateTime.Date.ToString());
                }

                if (f2Deadline.EditValue == null)
                {
                    f2deadline = null;
                }
                else
                {
                    f2deadline = DateTime.Parse(this.f2Deadline.DateTime.Date.ToString());
                }

                if (f5Deadline.EditValue == null)
                {
                    f5deadline = null;
                }
                else
                {
                    f5deadline = DateTime.Parse(this.f5Deadline.DateTime.Date.ToString());
                }

                if (overDeadline.EditValue == null)
                {
                    overdeadline = null;
                }
                else
                {
                    overdeadline = DateTime.Parse(this.overDeadline.DateTime.Date.ToString());
                }

                if (vnDeadline.EditValue == null)
                {
                    vndeadline = null;
                }
                else
                {
                    vndeadline = DateTime.Parse(this.vnDeadline.DateTime.Date.ToString());
                }

                if (storeDeadline.EditValue == null)
                {
                    storedeadline = null;
                }
                else
                {
                    storedeadline = DateTime.Parse(this.storeDeadline.DateTime.Date.ToString());
                }

                if (assDeadline.EditValue == null)
                {
                    assdeadline = null;
                }
                else
                {
                    assdeadline = DateTime.Parse(this.assDeadline.DateTime.Date.ToString());
                }
                
                if (f4Order.Checked)
                {
                    f4 = 1;
                }
                else
                {
                    f4 = 0;
                }

                note = this.noteValue.Text;        

                try
                {
                    myConnection.Open();
                    string sql = "UPDATE [241_ExportRobotPlan] SET"
                        + " PlanNo='" + planno + "', POID='" + poid + "', CusPlanNo='" + cusplan + "', CusOrderNo='" + cusorder + "',"
                        + " UnitPrice=" + unitprice + ", CurrencyID=" + currency + ", DeliveryTermID='" + delivery + "',"
                        + " TransportID='" + transp + "', FixDeadline=@fixdeadline, F2Deadline=@f2deadline, F5Deadline=@f5deadline,"
                        + " OImportDeadline=@overdeadline, VNImportDeadline=@vndeadline, StoreDeadline=@storedeadline,"
                        + " AssDeadline=@assdeadline, F4Order=" + f4 + ", Note='" + note + "'"
                        + " WHERE Number='" + number + "'";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@fixdeadline", SqlDbType.DateTime).Value = (fixdeadline == null) ? (object)DBNull.Value : fixdeadline.Value.Date;
                    cmd_sql.Parameters.Add("@f2deadline", SqlDbType.DateTime).Value = (f2deadline == null) ? (object)DBNull.Value : f2deadline.Value.Date;
                    cmd_sql.Parameters.Add("@f5deadline", SqlDbType.DateTime).Value = (f5deadline == null) ? (object)DBNull.Value : f5deadline.Value.Date;
                    cmd_sql.Parameters.Add("@overdeadline", SqlDbType.DateTime).Value = (overdeadline == null) ? (object)DBNull.Value : overdeadline.Value.Date;
                    cmd_sql.Parameters.Add("@vndeadline", SqlDbType.DateTime).Value = (vndeadline == null) ? (object)DBNull.Value : vndeadline.Value.Date;
                    cmd_sql.Parameters.Add("@storedeadline", SqlDbType.DateTime).Value = (storedeadline == null) ? (object)DBNull.Value : storedeadline.Value.Date;
                    cmd_sql.Parameters.Add("@assdeadline", SqlDbType.DateTime).Value = (assdeadline == null) ? (object)DBNull.Value : assdeadline.Value.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Export Robot Plan updated success.");
                    this.Dispose();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }                    
                    MessageBox.Show("Cannot Update Export Robot Plan. Please try again.");
                }
            }
            else
            {                
                MessageBox.Show(error_add);
            }
        }
    }
}
